<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="90px">
          <!--          <el-form-item label="健身房名称" prop="gymName">
            <el-input v-model="queryParams.gymName" placeholder="请输入健身房名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="教练id" prop="coachId">
            <el-input v-model="queryParams.coachId" placeholder="请输入教练id" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->

          <el-form-item label="会员卡名称" prop="cardName">
            <el-input v-model="queryParams.cardName" placeholder="请输入会员卡名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <!--       <el-form-item label="有效期" prop="cardEffectiveDay">
            <el-input v-model="queryParams.cardEffectiveDay" placeholder="请输入有效期" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--         <el-form-item label="对象存储主键" prop="ossId">
            <el-input v-model="queryParams.ossId" placeholder="请输入对象存储主键" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--        <el-form-item label="次数" prop="availableCount">
            <el-input v-model="queryParams.availableCount" placeholder="请输入次数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="办卡金额" prop="price">
            <el-input v-model="queryParams.price" placeholder="请输入办卡金额" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:clubCard:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:clubCard:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:clubCard:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:clubCard:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="clubCardLista" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="会员卡id" align="center" prop="id" v-if="true" /> -->
        <!-- <el-table-column label="教练id" align="center" prop="coachId" /> -->
        <el-table-column label="会员卡名称" align="center" prop="cardName" />
        <el-table-column label="会员卡类型" align="center" prop="memberCourseType">
          <template #default="scope">
            <dict-tag :options="g_vipka_type" :value="scope.row.memberCourseType" />
          </template>
        </el-table-column>
        <el-table-column label="卡种" align="center" prop="cardType">
          <template #default="scope">
            <dict-tag :options="g_kazhong_type" :value="scope.row.cardType" />
          </template>
        </el-table-column>
        <el-table-column label="有效期(天)" align="center" prop="cardEffectiveDay" />
        <!-- <el-table-column label="对象存储主键" align="center" prop="ossId" /> -->
        <el-table-column label="次数" align="center" prop="availableCount" />

        <el-table-column label="办卡金额" align="center" prop="price" />
        <el-table-column label="会员卡状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="g_status_type" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="周卡限制次数" align="center" prop="weekCount" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:clubCard:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:clubCard:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改会员卡信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="clubCardFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="图片" prop="ossId">
          <imageUpload v-model="form.ossId" ref="childValue" :limit='1' />
        </el-form-item>

        <!-- <el-form-item label="健身房名称" prop="gymName">
          <el-input v-model="form.gymName" placeholder="请输入健身房名称" />
        </el-form-item> -->
        <el-form-item label="会员卡名称" prop="cardName">
          <el-input v-model="form.cardName" placeholder="请输入会员卡名称" @input="trimInput('cardName')"/>
        </el-form-item>

        <el-form-item label="会员卡类型" prop="memberCourseType">
          <el-select v-model="form.memberCourseType" placeholder="请选择" @change="selectCourseType" :disabled='dataoo.isshow'>
            <el-option v-for="dict in g_vipka_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="每节时长(分)" prop="duration" v-if="form.memberCourseType==1">
          <el-input v-model="form.duration" placeholder="请输入每节时长(分)" type="number" :min="0" style='width:215px' />
        </el-form-item>

        <el-form-item label="课程教练" prop="coachId" v-if="form.memberCourseType==1">
         <!-- <span>{{form.coachId}}</span> -->
          <el-select v-model="form.coachId" placeholder="请选择"  filterable multiple>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="卡种" prop="cardType" v-if="form.memberCourseType==0">
          <el-select v-model="form.cardType" placeholder="请选择" @change="selectka" :disabled='dataoo.isshow'>
            <el-option v-for="dict in g_kazhong_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员卡状态" prop="status" v-if="dataoo.isshow==true">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option v-for="dict in g_status_type" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="cardEffectiveDay">
          <el-input v-model="form.cardEffectiveDay" placeholder="请输入有效期" type="number" :min="0" />
        </el-form-item>
        <el-form-item label="次数" prop="availableCount" v-if="form.cardType==1">
          <el-input v-model="form.availableCount" placeholder="请输入次数" type="number" :min="0" />
        </el-form-item>


        <el-form-item label="办卡金额" prop="price">
          <el-input v-model="form.price" placeholder="请输入办卡金额" type="number" :min="0" />
        </el-form-item>
       <el-form-item label="退款规则" prop="gymRefundRuleId" >
          <!-- <span>{{form.gymRefundRuleId}}</span> -->
          <el-select v-model="form.gymRefundRuleId" placeholder="请选择"  filterable clearable>
            <el-option v-for="dict in tuiList" :key="dict.id" :label="dict.refundRuleName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周限制次数" prop="weekCount" v-if="form.cardType==1">
          <el-input v-model="form.weekCount" placeholder="请输入次数" type="number" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" @input="trimInput('remark')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClubCard" lang="ts">
  import { listClubCard, getClubCard, delClubCard, addClubCard, updateClubCard } from '@/api/primary/clubCard';
  import { listGymRefundRule } from '@/api/primary/gymRefundRule';
  import { ClubCardVO, ClubCardQuery, ClubCardForm } from '@/api/primary/clubCard/types';
  import { listRole } from "@/api/system/role";
  import { listCoach } from '@/api/primary/coach';
  import { nextTick } from 'vue';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { g_vipka_type, g_kazhong_type, g_status_type } = toRefs<any>(proxy?.useDict("g_vipka_type", "g_kazhong_type", "g_status_type"));
  let clubCardLista = ref<ClubCardForm[]>([]);
  //let clubCardLista = reactive<any>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const coachList = ref<any>([]);
  const tuiList = ref<any>([]);
  const roleCan = ref<any>();
  const roleList = ref<any>();
  const ids = ref<Array<string | number>>([]);
  const idsname = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const queryFormRef = ref<ElFormInstance>();
  const clubCardFormRef = ref<ElFormInstance>();
  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const dataoo = reactive({
    status: [ //
      { value: 0, label: '上架中' },
      { value: 1, label: '下架' },
    ],
    isshow: false
  })
  const initFormData : ClubCardForm = {
    id: undefined,
    coachId: undefined,
    //gymName: undefined,
    cardName: undefined,
    gymRefundRuleId: undefined,
    memberCourseType: undefined,
    cardType: undefined,
    cardEffectiveDay: undefined,
    ossId: undefined,
    availableCount: null,
    weekCount: null,
    price: undefined,
    status: 0,
    remark: undefined,
    duration: undefined,
  }

  const data = reactive<PageData<ClubCardForm, ClubCardQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      duration: undefined,
      gymRefundRuleId: undefined,
      coachId: undefined,
      //gymName: undefined,
      cardName: undefined,
      memberCourseType: undefined,
      cardType: undefined,
      cardEffectiveDay: undefined,
      ossId: undefined,
      availableCount: null,
      weekCount: null,
      price: undefined,
      status: undefined,
      params: {
      }
    },
    rules: {

      coachId: [
        { required: true, message: "教练不能为空", trigger: "blur" }
      ],
      duration: [
        { required: true, message: "每节时长不能为空", trigger: "blur" }
      ],
      // gymName: [
      //   { required: true, message: "健身房名称不能为空", trigger: "blur" }
      // ],
      cardName: [
        { required: true, message: "会员卡名称不能为空", trigger: "blur" }
      ],
      memberCourseType: [
        { required: true, message: "会员卡类型不能为空", trigger: "change" }
      ],
      cardType: [
        { required: true, message: "卡种不能为空", trigger: "change" }
      ],
      cardEffectiveDay: [
        { required: true, message: "有效期不能为空", trigger: "blur" }
      ],
      ossId: [
        { required: true, message: "会员卡图片不能为空", trigger: "blur" }
      ],
      availableCount: [
        { required: true, message: "次数不能为空", trigger: "blur" }
      ],
      price: [
        { required: true, message: "办卡金额不能为空", trigger: "blur" }
      ],
      status: [
        { required: true, message: "会员卡状态不能为空", trigger: "change" }
      ],
      remark: [
        { required: false, message: "备注不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询会员卡信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listClubCard(queryParams.value);
    clubCardLista = res.rows;
    console.log(clubCardLista, '会员卡列表')
    total.value = res.total;
    loading.value = false;
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    clubCardFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  const selectka = () => {
    if (form.value.cardType == 0) {
      form.value.availableCount = ''
      form.value.weekCount = ''
    }
  }
  const selectCourseType = () => {
    if (form.value.memberCourseType == 0) {
      form.value.duration = ''
      form.value.coachId = ''
      form.value.cardType=''
    }else if(form.value.memberCourseType==1){
      form.value.cardType=1
    }
  }
  /** 查询退票规则列表 */
  const getListtui = async () => {

    const res = await listGymRefundRule(queryParams.value);
    tuiList.value = res.rows;
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : ClubCardVO[]) => {
    ids.value = selection.map(item => item.id);
    idsname.value = selection.map(item => item.cardName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  const getListc = async () => {
    console.log('111111')
    const res = await listCoach(queryParams.value);
    coachList.value = res.rows;

  }
  // const getListb = () => {
  //   // queryParams.value.startDate=''
  //   // queryParams.value.endDate=''
  //   listRole(proxy?.addDateRange(queryParams.value)).then(res => {
  //     roleList.value = res.rows
  //     roleCan.value = roleList.value.find(item => item.roleName === '健身教练');
  //     console.log(roleCan.value.roleId, '健身教练id')
  //     getListc()
  //   })
  // }
  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dataoo.isshow = false
    dialog.title = "添加会员卡信息";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: ClubCardVO) => {
    reset();
    dataoo.isshow = true
    const _id = row?.id || ids.value[0]
    const res = await getClubCard(_id);
    Object.assign(form.value, res.data);
    form.value.coachId=res.data.coachList
    dialog.visible = true;
    dialog.title = "修改会员卡信息";
  }

  /** 提交按钮 */
  const submitForm = () => {
    clubCardFormRef.value?.validate(async (valid : boolean) => {

      if (valid) {
        if(form.value.cardEffectiveDay<1){
          proxy?.$modal.msgError("请确认有效期输入是否正确");
          return
        }
        if(form.value.availableCount){
          if(form.value.availableCount<1){
            proxy?.$modal.msgError("请确认次数输入是否正确");
            return
          }
        }
        if(form.value.weekCount){
          if(form.value.weekCount<1){
            proxy?.$modal.msgError("请确认周卡限制次数输入是否正确");
            return
          }
        }

        if(form.value.price<0.01){
          proxy?.$modal.msgError("请确认办卡金额输入是否正确");
          return
        }
        buttonLoading.value = true;
        form.value.coachList=undefined
        if (form.value.id) {
          if (form.value.memberCourseType == 1) {
            form.value.cardType = 1
            form.value.coachId = form.value.coachId.join(',');
            console.log(form.value.coachId, 'aaaaaaaaaaa')

          }else {
            form.value.coachId = ''
          }
          form.value.gymId = undefined
          await updateClubCard(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          if (form.value.memberCourseType == 1) {
            form.value.cardType = 1
            form.value.coachId = form.value.coachId.join(',');
            console.log(form.value.coachId, 'aaaaaaaaaaa')
          } else {
            form.value.coachId = ''
          }

          await addClubCard(form.value).finally(() => buttonLoading.value = false);
          queryParams.value.cardName = ''
          queryParams.value.price = ''
          proxy?.$modal.msgSuccess("添加成功");
        }
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: ClubCardVO) => {
    const _ids = row?.id || ids.value;
    const name = row?.cardName || idsname.value;
    await proxy?.$modal.confirm('是否确认删除会员卡信息编号为"' + name + '"的数据项？一旦删除，绑定该会员卡的会员，将全部删除,是否确认删除!!!').finally(() => loading.value = false);
    await proxy?.$modal.confirm('您已了解删除后果，确认删除吗').finally(() => loading.value = false);
    await delClubCard(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/clubCard/export', {
      ...queryParams.value
    }, `clubCard_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    queryParams.value.pageNum=undefined
    queryParams.value.pageSize=undefined
    getListc()
    getListtui()
    queryParams.value.pageNum=1
    queryParams.value.pageSize=10
    getList();
  });
</script>
